package com.ala.controller;


import com.ala.dao.DeviceMapper;
import com.ala.emqx.MqttGateway;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class EmqxController {


    @Autowired
    MqttGateway mqttGateway;

    @Resource
    DeviceMapper deviceMapper;

    @RequestMapping("/say")
    public String say(@RequestParam(name = "topic",required = false,defaultValue = "topic_out") String topic,@RequestParam(name = "msg",required = false,defaultValue = "from server mqtt") String msg){


        mqttGateway.sendToMqtt(topic,1,msg);
        return "emqx demo";
    }

    @RequestMapping(value = "/emqwebhook")
    public void  emqwebhook(@RequestBody String json){
//        mqttGateway.sendToMqtt("topic_out",1,ps);
        System.out.println(json);
        JSONObject ps = JSON.parseObject(json);

        String action = ps.getString("action");
        String sn = ps.getString("client_id");
        switch (action){
            case  "client_disconnected":
                deviceMapper.upodateOnlineBySn(sn,0);
                break;
            case  "client_connected":
                deviceMapper.upodateOnlineBySn(sn,1);
                break;
        }

    }
}
